﻿Partial Public Class DatabaseToolsPage

    Private Sub btnCheckDatabase_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCheckDatabase.Click
        Dim db As New SpatialAlbum.Core.Database
        Dim okay As Boolean = db.CheckDatabase(g_connection)
        If okay Then
            SetLabel(lblCheckDatabaseStatus, "Database is okay.", False)
        Else
            SetLabelError(lblCheckDatabaseStatus, "Database problems found.", True)
        End If
    End Sub

    Private Sub btnLoadSamples_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnLoadSamples.Click
        g_mainpage.ShowPage(EnumPage.eImageLoader)
        AddHandler g_imageloader.FinishedLoadingImages, AddressOf OnFinishedLoadingImages
        SetLabel(lblLoadSamplesStatus, "Loading images...", False)
        g_imageloader.AddImage(IO.Path.Combine(IO.Directory.GetCurrentDirectory(), My.Settings.RTS_TestPhoto1), g_connection)
        g_imageloader.AddImage(IO.Path.Combine(IO.Directory.GetCurrentDirectory(), My.Settings.RTS_TestPhoto2), g_connection)
        g_imageloader.AddImage(IO.Path.Combine(IO.Directory.GetCurrentDirectory(), My.Settings.RTS_TestPhoto3), g_connection)
    End Sub


    Private Sub btnClearPhotos_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClearPhotos.Click
        Dim stats As DatabaseStatistics = DatabaseStatistics.GetStatistics(g_connection)
        Dim table As String = Schema.Photo
        Dim n As Integer = stats.Count(table)
        SetLabel(lblClearPhotosStatus, "Clearing " & n & " row(s) from the " & table & " table...", False)
        Dim db As New SpatialAlbum.Core.Database
        Dim okay As Boolean = db.ClearPhotoTable(g_connection)
        If okay Then
            SetLabel(lblClearPhotosStatus, "Cleared " & stats.Count(table) & " row(s) from the " & table & " table.", False)
        Else
            SetLabelError(lblClearPhotosStatus, "A problem occured clearing the Photos table.", True)
        End If
        g_currentphoto = Nothing
    End Sub

    Private Sub OnFinishedLoadingImages(ByVal njobs As Integer)
        RemoveHandler g_imageloader.FinishedLoadingImages, AddressOf OnFinishedLoadingImages
        SetLabel(lblLoadSamplesStatus, "Images loaded.", False)
    End Sub

    Public Delegate Sub DlgShowLog()
    Private Shared Sub ShowLog()
        g_mainpage.ShowPage(EnumPage.eLog)
    End Sub

    Private Sub btnCreateDatabase_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCreateDatabase.Click
        Dim rc As MessageBoxResult = MessageBox.Show( _
            "This will create a new database. Any data in the current database will be lost." & vbCrLf & vbCrLf & _
            "Do you want to create a new database?", _
            "Create Database", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No)
        If rc <> MessageBoxResult.Yes Then Return

        SetLabel(lblCreateDatabaseStatus, "Creating database...", True)

        Dim thr As New System.Threading.Thread(AddressOf CreateDatabase)
        thr.Start(cbxKeepAlbumData.IsChecked)
        g_mainpage.ShowPage(EnumPage.eLog)
    End Sub

    Private Sub CreateDatabase(ByVal keepalbums As Boolean)
        Try
            g_mainpage.SetStatusbarMessage("creating database...")
            g_logpage.UpdateFrequently = True
            Static db As New SpatialAlbum.Core.Database
            db.CreateDatabase(True, keepalbums, g_connection)
            SetLabel(lblCreateDatabaseStatus, "Database created.", False)
            g_mainpage.SetStatusbarMessage("database created")
            MessageBox.Show("Database created.", "Create Database", MessageBoxButton.OK, MessageBoxImage.Information)
        Catch ex As Exception
            SetLabelError(lblCreateDatabaseStatus, "An error occured creating the database.", True)
            ReportException(ex)
            'Throw ex
        Finally
            g_logpage.UpdateFrequently = False
        End Try
    End Sub

    Private Delegate Sub DlgSetLabel(ByVal label As Label, ByVal message As String, ByVal addloglink As Boolean)
    Private Shared Sub SetLabel(ByVal label As Label, ByVal message As String, ByVal addloglink As Boolean)
        If Not label.Dispatcher.CheckAccess() Then
            label.Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Send, New DlgSetLabel(AddressOf SetLabel), label, message, addloglink)
        Else
            Dim content As New TextBlock()
            content.Inlines.Add(New Run(message))
            If addloglink Then
                content.Inlines.Add(New Run(" "))
                content.Inlines.Add(MakeLinkToLog(New DlgShowLog(AddressOf ShowLog)))
            End If
            label.Content = content
            label.Style = My.Application.Resources.Item("LabelStatusOkay")
        End If
    End Sub

    Private Shared Sub SetLabelError(ByVal label As Label, ByVal message As String, ByVal addloglink As Boolean)
        If Not label.Dispatcher.CheckAccess() Then
            label.Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Send, New DlgSetLabel(AddressOf SetLabelError), label, message, addloglink)
        Else
            Dim content As New TextBlock()
            content.Inlines.Add(New Run(message))
            If addloglink Then
                content.Inlines.Add(New Run(" "))
                content.Inlines.Add(MakeLinkToLog(New DlgShowLog(AddressOf ShowLog)))
            End If
            label.Content = content
            label.Style = My.Application.Resources.Item("LabelStatusError")
        End If
    End Sub

    Public Shared Function MakeLinkToLog(ByVal callback As DlgShowLog) As TextBlock
        Dim tb As New TextBlock()
        tb.Inlines.Add(New Run("Click "))
        Dim link As New Hyperlink(New Run("here"))
        AddHandler link.Click, AddressOf ShowLog
        tb.Inlines.Add(link)
        tb.Inlines.Add(New Run(" to view the log."))
        Return tb
    End Function

    Private Sub btnRefreshStatistics_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRefreshStatistics.Click
        Dim tbl As Table = StatisticsTable1
        Dim rows As TableRowCollection = tbl.RowGroups(0).Rows
        rows.Clear()
        Dim row As TableRow
        Dim stats As DatabaseStatistics = DatabaseStatistics.GetStatistics(g_connection)
        For Each tablename As String In Database.TableNames
            row = New TableRow
            row.Cells.Add(New TableCell(New Paragraph(New Run(tablename))))
            row.Cells.Add(New TableCell(New Paragraph(New Run(stats.Count(tablename)))))
            rows.Add(row)
        Next

    End Sub
End Class
